package com.baiyun.bs.controller.admin;


import com.baiyun.bs.domain.*;
import com.baiyun.bs.viewmodel.admin.message.MessagePageRequestVM;
import com.baiyun.bs.viewmodel.admin.message.MessageResponseVM;
import com.baiyun.bs.viewmodel.admin.message.MessageSendVM;
import com.baiyun.bs.base.BaseApiController;
import com.baiyun.bs.base.RestResponse;
import com.baiyun.bs.service.MessageService;
import com.baiyun.bs.service.NoticeService;
import com.baiyun.bs.service.UserService;
import com.baiyun.bs.utility.DateTimeUtil;
import com.baiyun.bs.utility.PageInfoHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController("AdminMessageController")
@RequestMapping(value = "/api/admin/message")
public class MessageController extends BaseApiController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private NoticeService noticeService;

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<MessageResponseVM>> pageList(@RequestBody MessagePageRequestVM model) {
        PageInfo<Message> pageInfo = messageService.page(model);
        List<Integer> ids = pageInfo.getList().stream().map(d -> d.getId()).collect(Collectors.toList());
        List<MessageUser> messageUsers = ids.size() == 0 ? null : messageService.selectByMessageIds(ids);
        PageInfo<MessageResponseVM> page = PageInfoHelper.copyMap(pageInfo, m -> {
            MessageResponseVM vm = modelMapper.map(m, MessageResponseVM.class);
            String receives = messageUsers.stream().filter(d -> d.getMessageId().equals(m.getId())).map(d -> d.getReceiveUserName())
                    .collect(Collectors.joining(","));
            vm.setReceives(receives);
            vm.setCreateTime(DateTimeUtil.dateFormat(m.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);
    }


    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public RestResponse send(@RequestBody @Valid MessageSendVM model) {
        User user = getCurrentUser();
        List<User> receiveUser = userService.selectByIds(model.getReceiveUserIds());
        Date now = new Date();
        Message message = new Message();
        message.setTitle(model.getTitle());
        message.setContent(model.getContent());
        message.setCreateTime(now);
        message.setReadCount(0);
        message.setReceiveUserCount(receiveUser.size());
        message.setSendUserId(user.getId());
        message.setSendUserName(user.getUserName());
        message.setSendRealName(user.getRealName());
        List<MessageUser> messageUsers = receiveUser.stream().map(d -> {
            MessageUser messageUser = new MessageUser();
            messageUser.setCreateTime(now);
            messageUser.setReaded(false);
            messageUser.setReceiveRealName(d.getRealName());
            messageUser.setReceiveUserId(d.getId());
            messageUser.setReceiveUserName(d.getUserName());
            return messageUser;
        }).collect(Collectors.toList());
        messageService.sendMessage(message, messageUsers);
        return RestResponse.ok();
    }

    @RequestMapping(value = "/getAllNotice", method = RequestMethod.POST)
    public RestResponse<List<Notice>> getAllNotice(@RequestBody Notice notice) {
        List<Notice> allNotices = noticeService.getAllNotices(notice );
        return RestResponse.ok(allNotices);
    }

    @RequestMapping(value = "/selectNotice/{nId}", method = RequestMethod.POST)
    public RestResponse<Notice> selectNoticeById(@PathVariable Long nId) {
        Notice notice = noticeService.selectNoticeById(nId);
        return RestResponse.ok(notice);
    }
    @RequestMapping(value = "/addNotice", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public RestResponse<Void> addNotice(@RequestBody Notice notice) {
        if (notice.getnId() != null) {
            noticeService.updateNotice(notice);
        }else {
            noticeService.addNotice(notice);
        }
        return RestResponse.ok();
    }

    @RequestMapping(value = "/updateNotice/{nId}" , method = RequestMethod.POST)
    public RestResponse<Void> updateNotice(@PathVariable Long nId, @RequestBody Notice notice) {
        notice.setnId(nId);
        noticeService.updateNotice(notice);
        return RestResponse.ok();
    }


    @RequestMapping(value = "/deleteNotice/{nId}", method = RequestMethod.POST)
    public RestResponse<Void> deleteNotice(@PathVariable Long nId) {
        try {
            noticeService.deleteNotice(nId);
            return RestResponse.ok();
        } catch (Exception e) {
            // 记录异常信息到日志文件
            return RestResponse.fail(500, "系统内部错误，删除通知失败");
        }
    }



}
